from .main import app


# 经过@app.task装饰过，就会被celery识别为任务，否则就是普通的函数
@app.task
def task1(a, b, c):
    print("任务1函数正在执行....")
    return a + b + c


"""
import json
from datetime import datetime, timedelta
period_obj = PeriodicTask.objects.create(
     interval=schedule,                  # we created this above.
     name='task23',                       # 唯一的任务名称，名字不能重复
     task='celery_tasks.tasks.task1',    # 任务的导包路径
     args=json.dumps([5, 10, 15]),  # 异步任务有参数时，可以通过args或者kwargs来设置
     #kwargs=json.dumps({
     #   'be_careful': True,
     #}),
     expires=datetime.utcnow() + timedelta(seconds=30), # 任务的持续时间
)
"""


@app.task
def task2():
    print("任务2函数正在执行....")


"""
period_obj1 = PeriodicTask.objects.create(
     interval=schedule,                  # we created this above.
     name='task30',                       # 唯一的任务名称，名字不能重复
     task='celery_tasks.tasks.task2',    # 任务的导包路径
     expires=datetime.utcnow() + timedelta(seconds=30), # 任务的持续时间
)
"""

# uric计划任务
import json
from host.models import Host
from django.conf import settings
from uric_api.utils.key import PkeyManager


@app.task(name='schedule_task')
def schedule_task(cmd, hosts_ids):
    """计划任务"""
    hosts_objs = Host.objects.filter(id__in=hosts_ids)
    result_data = []
    private_key, public_key = PkeyManager.get(settings.DEFAULT_KEY_NAME)
    for host_obj in hosts_objs:
        cli = host_obj.get_ssh(private_key)
        code, result = cli.exec_command(cmd)
        result_data.append({
            'host_id': host_obj.id,
            'host': host_obj.ip_addr,
            'status': code,
            'result': result
        })
        print('>>>>', code, result)

    return json.dumps(result_data)
